package cn.how2j.diytomcat;

import cn.hutool.core.util.NetUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by SilentJhin on 2020/7/31 9:54
 */
public class Bootstrap {

    public static void main(String[] args) {
        try {
            int port = 18080;
            if (!NetUtil.isUsableLocalPort(port)){
                System.out.println("端口被占用");
                System.out.println("排查并关闭本端口的办法请用：\\r\\nhttps://how2j.cn/k/tomcat/tomcat-portfix/545.html");
                return;
            }
            ServerSocket ss = new ServerSocket(port);
            while(true){
                Socket s = ss.accept();
                // 接收客户端提交的信息
                InputStream is = s.getInputStream();
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                // 保存到数组里并打印
                is.read(buffer);
                String requestString = new String(buffer, "utf-8");
                System.out.println("浏览器输入信息:" + requestString);
                // 准备给客户端输出消息
                OutputStream os = s.getOutputStream();
                String response_head = "HTTP/1.1 200 OK\r\n" + "Content-Type:text/html\r\n\r\n";
                String responseString = "Hello DIY Tomcat from how2j.cn";
                responseString = response_head + responseString;
                System.out.println("start");
                System.out.println(responseString);
                System.out.println("end");
                // 信息写到socket里.
                os.write(responseString.getBytes());
                os.flush();
                s.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
